#!/bin/bash 

#第一个参数是邮件文件路径，第二个参数是关键字
function get_start_line(){
    local mail_file=$1 
    local para=$2
    local cur_line=""
    local index=0
    local ret

    case $para in 
        subject) 
            index=$(grep -n 'Subject: ' ${mail_file})
            ret=${index%%:*}
        ;;
        content) 
            ret=$(grep -n 'Content-Type: text/plain;' ${mail_file})
            if [ ${#ret} -eq 0 ]; then #没找到，说明邮件内容为空，直接返回0
                return 0
            fi
            index=${ret%%:*}
            while [ true ]; do
                let "index++"
                cur_line=$(sed -n "$index""p" ${mail_file})
                if [ ${#cur_line} -eq 0 ]; then #找到空行，说明邮件正文数据开始
                    break
                fi
            done
            ret=${index}
        ;;
        #filename) ret=$(grep -n 'filename' ${mail_file})
        #;;
        *)  echo "wrong para!!"
        ;;
    esac

    return ${ret}
}

#第一个参数是邮件文件路径，第二个参数是关键字，第三个参数是start_line
function get_end_line(){
    local mail_file=$1 
    local para=$2
    local start_line=$3
    local flag
    local str
    local ret

    case $para in 
        subject) 
            #寻找类似"?GBK?B?这样的标记"
            flag=$(sed -n "$start_line""p" $mail_file | cut -d '?' -f 2)
            #echo "flag: $flag"
            while [ true ]; do
                let "start_line++"
                #在下一行寻找标记
                str=$(sed -n "$start_line""p" $mail_file | cut -d '?' -f 2)
                #echo "str: $str"
                if [[ $str != $flag ]]; then #若有相同的标记，说明数据未完；若没有相同的标记，说明数据完结
                    break
                fi
            done
            let "start_line--"
            return $start_line
        ;;
        content) 
            if [ $start_line -eq 0 ]; then return 0; fi #开始行为0，说明邮件内容为空，直接返回0
            while [ true ]; do
                let "start_line++"
                str=$(sed -n "$start_line""p" $mail_file)
                if [[ ${str:0:6} = "------" ]]; then #找到以"------"开头的行，说明数据结束
                    break
                fi
            done
            let "start_line--"
            return $start_line
        ;;
        #filename) ret=$(grep -n 'filename' ${mail_file})
        #;;
        *)  echo "wrong para!!"
        ;;
    esac

    return ${ret%%:*}
}

g_work_dir="/home/kjj-18/my_shell"

function decode_XQX(){
    local src=$1  
    local dst=""  
    local len=${#src}
    local i=0 

    cd ${g_work_dir} #将当前目录切换至脚本所在目录
    :>Qsrc.txt
    #:>dst.txt

    #echo "src:${src}"
    #echo "len:${len}"
    while [ $i -lt $len ]; do
        if [[ ${src:$i:1} = "=" ]]; then
            let "i++"
            echo -e -n "\x"${src:$i:2}>>Qsrc.txt
            i=$(expr $i + 2)
        else
            echo -n ${src:$i:1}>>Qsrc.txt
            let "i++"
        fi
    done

    #iconv -f GB2312 -t UTF-8 src.txt>dst.txt
    dst=$(cat Qsrc.txt)
    cd - > /dev/null    #将当前目录切换回原目录
    echo $dst
}

function parse_subject(){
    local mail_file=$1
    local start_line
    local end_line
    local flag
    local zh_encode
    local src
    local dst

    cd ${g_work_dir} #将当前目录切换至脚本所在目录
    :>src.txt
    :>dst.txt

    get_start_line $mail_file "subject"
    start_line=$?
    #echo "get start line: $start_line"
    get_end_line $mail_file "subject" $start_line
    end_line=$?
    #echo "get end line: $end_line"

    flag=$(sed -n "$start_line""p" $mail_file | cut -d '?' -f 3)
    zh_encode=$(sed -n "$start_line""p" $mail_file | cut -d '?' -f 2)
    while [ ${start_line} -le ${end_line} ]; do
       if [[ $flag = "B" ]]; then   #标记为"B"，以base64解码
           src=$(sed -n "$start_line""p" $mail_file | cut -d '?' -f 4 | base64 -d)
       elif [[ $flag = "Q" ]]; then #标记为"Q"，自己解码
           src=$(sed -n "$start_line""p" $mail_file | cut -d '?' -f 4)
           src=$(decode_XQX $src)
       else
           src=$(sed -n "$start_line""p" $mail_file)
           src=${src#* }
       fi
       echo $src>>src.txt 
       let "start_line++"
    done

    if [[ $zh_encode = "UTF-8" || $zh_encode = "" ]]; then
        cp src.txt dst.txt
    else
        iconv -f GB2312 -t UTF-8 src.txt>dst.txt
    fi
    #cat dst.txt
    sed -i ':t;N;s/\n//;b t' dst.txt #去掉换行符
    sed -i 's/[ :?,@#$&()\|;"""<>]/_/g' dst.txt #去掉空格等不宜做目录名的符号
    dst=$(cat dst.txt)

    cd - > /dev/null    #将当前目录切换回原目录
    echo $dst
    #echo "dst string: $dst"
}

function get_content_charset(){
    local mail_file=$1
    local flag_line
    local index
    local charset
    local ret

    index=$(grep -n 'Content-Type: text/plain;' ${mail_file})
    index=${index%%:*}
    flag_line=$(sed -n "$index""p" $mail_file)
    charset=${flag_line##*;}
    if [ ${#charset} -eq 0 ]; then
        let "index++"
        charset=$(sed -n "$index""p" $mail_file)
    fi
    charset=${charset//\"/}
    ret=${charset##*=}    

    echo $ret
}

function parse_content(){
    local mail_file=$1
    local start_line
    local end_line
    local src
    local dst
    local charset
    
    cd ${g_work_dir} #将当前目录切换至脚本所在目录 
    :>src.txt
    :>tmp.txt
    :>dst.txt

    get_start_line $mail_file "content"
    start_line=$?
    get_end_line $mail_file "content" $start_line
    end_line=$?
    #echo "[content]start line: $start_line, end_line: $end_line"
    if [[ $start_line -ne 0 && $end_line -ne 0 ]]; then
        while [ ${start_line} -le ${end_line} ]; do
           #src=$(sed -n "$start_line""p" $mail_file | base64 -d)
           src=$(sed -n "$start_line""p" $mail_file)
           #echo "src string: $src"
           echo $src>>tmp.txt
           let "start_line++"
        done
        cat tmp.txt | base64 -d>src.txt #邮件正文必须整体解码，因此需要一个tmp.txt做中转
        charset=$(get_content_charset $mail_file)
        if [[ $charset != "UTF-8" ]]; then  #UTF-8编码不需要转码
            iconv -f GBK -t UTF-8 src.txt>dst.txt
        else
            cp src.txt dst.txt
        fi
    fi

    if [ ! -s dst.txt ]; then 
        echo "$(cowsay -f stegosaurus 邮件中没有填写内容……)">dst.txt
    fi
    
    cd - > /dev/null    #将当前目录切换回原目录
    cat ${g_work_dir}"/dst.txt"
}

function parse_filename(){
    local src=$1
    local dst=""
    local flag=""
    local tmp=""
    local i=1

    cd ${g_work_dir} #将当前目录切换至脚本所在目录
    :>tmp.txt
    :>src.txt
    :>dst.txt

    if [[ ${src:0:8} = "=XGBKXBX" ]]; then
        flag="=XGBKXBX" 
    elif [[ ${src:0:8} = "=XGBKXQX" ]]; then
        flag="=XGBKXQX" 
    elif [[ ${src:0:12} = "=Xgb18030XBX" ]]; then
        flag="=Xgb18030XBX" 
    elif [[ ${src:0:10} = "=XUTF-8XBX" ]]; then
        flag="=XUTF-8XBX"
    fi
    
    if [[ ${flag} != "" ]]; then
        src=${src//${flag}/?}
        src=${src//XX?/}
        src=${src//X=/?}
        src=${src#*?}
        echo $src>tmp.txt
    fi

    #标记为"B"，以base64解码
    if [[ ${flag} = "=XGBKXBX" || ${flag} = "=Xgb18030XBX" || ${flag} = "=XUTF-8XBX" ]]; then 
        while [ true ]; do
            tmp=$(cut -d '?' -f $i tmp.txt | base64 -d)
            if [ ${#tmp} -eq 0 ]; then break; fi
            echo ${tmp}>>src.txt
            let "i++"
        done
    elif [[ ${flag} = "=XGBKXQX" ]]; then #标记为"Q"，自己解码
        while [ true ]; do
            tmp=$(cut -d '?' -f $i tmp.txt) 
            tmp=$(decode_XQX $tmp)
            if [ ${#tmp} -eq 0 ]; then break; fi
            echo ${tmp}>>src.txt
            let "i++"
        done
    fi

    if [[ $flag = "=XUTF-8XBX" ]]; then  
        cp src.txt dst.txt
    elif [[ $flag = "" ]]; then
        echo ${src}>dst.txt
    else
        iconv -f GBK -t UTF-8 src.txt>dst.txt
    fi

    sed -i ':t;N;s/\n//;b t' dst.txt #去掉换行符
    sed -i 's/[ :?,@#$&()\|;"""<>]/_/g' dst.txt #去掉空格等不宜做文件名的符号
    dst=$(cat dst.txt)

    cd - > /dev/null    #将当前目录切换回原目录
    echo $dst
}

function file_type(){
    local file=$1
    local flag=${file##*.}
    local ret=""

    if [[ $flag = "doc" || $flag = "docx" || $flag = "wps" ]]; then
        ret="doc"
    elif [[ $flag = "pdf" || $flag = "PDF" ]]; then
        ret="pdf"
    elif [[ $flag = "jpg" || $flag = "jpeg" || $flag = "JPG" || $flag = "png" || $flag = "PNG" ]]; then 
        ret="img"
    elif [[ $flag = "zip" || $flag = "rar" || $flag = "ZIP" || $flag = "RAR" ]]; then
        ret="cmprs"
    else
        ret="unknown"
    fi

    echo $ret
}

function unzip_docx(){
    local docx_file=$1
    local docx_index=$2
    local unzip_dir="unzip_docx-"$docx_index
    local img_exist=0
    local ret=""

    unzip $docx_file -d $unzip_dir > /dev/null
    img_exist=$(find ${unzip_dir}"/word" -name "media" | wc -l)
    if [ $img_exist -ne 0 ]; then
        ret=${unzip_dir}"/word/media"
    fi
     
    echo $ret
}

function correct_mistake(){
    local file=$1

    sed -i 's/(/（/g;s/)/）/g;s/,/，/g;s/\[/〔/g;s/\]/〕/g;s/【/〔/g;s/】/〕/g;s/\;/；/g;s/:/：/g;s/?/？/g;s/</〈/g;s/>/〉/g;' $file 
     
    return $?
} 

function uncompress(){
    local file=$1
    local dir=$2
    local flag=${file##*.}

    if [[ $flag = "zip" ]]; then
        unzip $file -d $dir > /dev/null
    elif [[ $flag = "rar" ]]; then
        unrar e $file $dir > /dev/null
    fi
}

#get_content_charset "/home/kjj-18/.getmail/maildir/tmp/test_gb18030"

#correct_mistake "test.txt"

#decode_XQX "Fw:=B9=AB=CA=BE"

#file_type "asdfasdfasdfasdfasdfasdfasdfasdfbc.png"

#get_end_line "test" "subject"
#echo "get subject end line: $?"

#parse_subject "XQX_subject-1"
#echo "mail subject: $(parse_subject "test_gb18030")"

#parse_content "content_empty"
#echo "mail content: $(parse_content "test.kjj-18-PC")"

#parse_filename "=XGBKXBXsbG2t76rw9y8vMr10dC+v6Gi1sfE3NbG1Oy7+bXYwuS7p9THzvcuZG9jeA==X="
#parse_filename "=XGBKXBXyqG/xry8zPzF+ri0zazS4sOpvP3H+L2oyei6/g==X=XX=XGBKXBXsbHKob/Js9bQ+Lei1bnKtdHpx/guZG9jeA==X="
#parse_filename "=XGBKXQX=D0=C5=CF=A2.rarX="
